package com.jh.netty.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 初始化
 */
public class ServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();  // 得到 Pipeline 链
        // 设置log监听器，并且日志级别为debug，方便观察运行流程
        pipeline.addLast("active",new ChannelActiveHandler());
        pipeline.addLast("logging", new LoggingHandler("DEBUG"));
        pipeline.addLast("socketChoose",new SocketChooseHandler());

//        1.websocket
//        pipeline.addLast("http-codec", new HttpServerCodec());
//        pipeline.addLast(new HttpRequestDecoder());
//        pipeline.addLast("aggregator",new HttpObjectAggregator(65536));
//        pipeline.addLast("http-chunked", new ChunkedWriteHandler());
//        pipeline.addLast(new HttpResponseEncoder());
//        pipeline.addLast(new WebSocketHandler());
////        // 往 Pipeline 链中添加一个解码器
//        pipeline.addLast("decoder", new HexStringDecoder());
////        pipeline.addLast( new ObjectEncoder()); //"decoder",
////        // 往 Pipeline 链中添加一个编码器
//        pipeline.addLast("encoder", new HexStringDecoder());
//        // 往 Pipeline 链中添加一个自定义的业务处理对象
        //用于处理websocket, /ws为访问websocket时的uri
//        pipeline.addLast("webSocketServerProtocolHandler", new WebSocketServerProtocolHandler("/ws"));
//        pipeline.addLast("handler", new WebSocketHandler());


        // 2.socket方式服务
        // 设置N秒没有读到数据，则触发一个READER_IDLE事件。
//        pipeline.addLast(new IdleStateHandler(80,0,0, TimeUnit.SECONDS));
//        pipeline.addLast("active",new ChannelActiveHandle());
//        pipeline.addLast("socketChoose",new SocketChooseHandler());
////
//        //tcpsocket编码解码handle，如果是websocket链接，会将其删除
//        pipeline.addLast("lengthEncode",new LengthFieldPrepender(4, false));
//        pipeline.addLast("lengthDecoder",new LengthFieldBasedFrameDecoder(2000, 0, 4,0, 4));
//        pipeline.addLast(new BytebufToByteHandler());
//
        //因为接收类型的泛型不对，所以在websocket握手的时候不会进入该handle
        //此handle为最后的socket消息分解，web和tcp通用
//        pipeline.addLast("byteToBuf",byteToByteBufHandle);
//        pipeline.addLast("protocolResolve",protocolResolveHandle);
    }
}